package com.shrio.dao.impl;

import com.shrio.dao.UserDao;
import com.shrio.entity.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luojie on 2018/3/6.
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.openSession();
    }


    @Override
    public User get(Long id) {
        return (User) getCurrentSession().get(User.class,id);
    }

    @Override
    public List<User> findAll() {
        return null;
    }

    @Override
    public Long save(User entity) {
        return (Long)getCurrentSession().save(entity);
    }

    @Override
    public void saveOrUpdate(User entity) {
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(Long id) {

        User person = get(id);
        getCurrentSession().delete(person);
    }

    @Override
    public User findByUserName(String username) {
        String hql = "from User where username=?";
        Session session = getCurrentSession();
        Transaction tx = null;
        ArrayList list = null;
        try {
            tx = session.beginTransaction();
            Query query = session.createQuery(hql);

            query.setParameter(0, username);

            list = (ArrayList) query.list();
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        if(list == null || list.size() == 0){
            return null;
        }
        return (User) list.get(0);
    }
}
